package com.tangtang.hystrix.provider.command;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import com.tangtang.hystrix.provider.utils.HttpClientUtils;
import com.tangtang.hystrix.provider.vo.BrandVO;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

public class BrandSemaphoreCommand extends HystrixObservableCommand<BrandVO> {


    private Long id;
    public BrandSemaphoreCommand(Long id){
        //设置信号量的话就不需要担心超时的问题了
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("brandGroup"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)));
        this.id = id;
    }

    @Override
    protected Observable<BrandVO> construct() {
       return Observable.unsafeCreate(new Observable.OnSubscribe<BrandVO>() {
            @Override
            public void call(Subscriber<? super BrandVO> observer) {
                try {
                    if (!observer.isUnsubscribed()) {
                        String request = HttpClientUtils.sendGetRequest("http://127.0.0.1:8086/api/v1/brand/"+id);
                        BrandVO brandVO  =  JSONObject.parseObject(request, BrandVO.class);
                        observer.onNext(brandVO);
                        observer.onCompleted();
                    }
                } catch (Exception e) {
                    observer.onError(e);
                }
            }
        } ).subscribeOn(Schedulers.io());


    }

    @Override
    protected Observable<BrandVO> resumeWithFallback() {
        return super.resumeWithFallback();
    }
}
